<template>
    <el-dialog :model-value="dialogVisible" :title="type == 'add' ? '新增预算' : '编辑预算'" width="800px"
        :before-close="handleClose" append-to-body>
        <el-form ref="formRef" :model="dataForm" label-width="100px" :rules="rules" :inline="false">
            <el-form-item label="新增方式" prop="methods">
                <el-select v-model="dataForm.methods" class="w100p">
                    <el-option v-for="item in addMethods" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="预算名称" prop="budgetName">
                <el-input v-model="dataForm.budgetName" placeholder="请输入" minlength="4" maxlength="50" />
            </el-form-item>
            <el-form-item label="控制方式" prop="controlBy" v-if="dataForm.methods == 2">
                <el-select v-model="dataForm.controlBy" class="w100p">
                    <el-option v-for="item in CTROL_METHOD_LIST" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>

            <el-form-item label="自定义时间" prop="date" v-if="dataForm.controlBy == 'CUSTOM_TIME_RANGE'">
                <el-date-picker v-model="dataForm.date" type="monthrange" range-separator="至" start-placeholder="开始"
                    end-placeholder="结束" style="width:100%" value-format="YYYY-MM" />
            </el-form-item>
            <el-form-item label="选择周期" prop="cycleType" v-if="dataForm.methods == '2'">
                <el-select v-model="dataForm.cycleType" filterable class="w100p">
                    <el-option v-for="item in weeksList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="选择年份" prop="years" v-if="dataForm.controlBy == 'CYCLE'">
                <el-select v-model="dataForm.years" clearable filterable class="w100p"
                    @change="selectYears(dataForm.years)">
                    <el-option v-for="item in yearOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="预算模板" prop="budgetTemplateId" v-if="dataForm.methods == '1'">
                <el-select v-model="dataForm.budgetTemplateId" clearable filterable class="w100p"
                    :disabled="dataForm.years==''">
                    <el-option v-for="item in templateList" :key="item.id" :label="item.templateName"
                        :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="预算类型" prop="budgetType">
                <el-select v-model="dataForm.budgetType" class="w100p" @change="selectBudgetType">
                    <el-option v-for="item in BUDGET_TYPE_LIST" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="公司" prop="orgCode">
             <companySearch :back-value="dataForm.orgCode" class="w100p"  @select="selectCompany"></companySearch>
            </el-form-item>
            <el-form-item label="成本中心" prop="costCenterIdList">
                <el-select v-model="dataForm.costCenterIdList" multiple class="w100p" filterable :disabled="dataForm.orgCode==''">
                    <el-option v-for="item in costCenterList " :key="item.id" :label="item.centerName"
                        :value="item.id" />
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="预算结转" prop="budgetRollEnabled">
                <el-switch v-model="dataForm.budgetRollEnabled" :active-value="true" :inactive-value="false" />
                <p class="prompt">开关打开后，当期未用完的预算自动累计到下期</p>
            </el-form-item> -->
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="submit()">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import api from "@/api/index";
import { ElMessage, ElMessageBox } from 'element-plus'
import { yearFun } from '@/util/index'
import { watch } from "vue";
import { TIME_WEEK_LIST, WEEK_LIST, BUDGET_TYPE_LIST, CTROL_METHOD_LIST } from './config'
import companySearch from '@/components/CompanySearch/index.vue'

const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    type: {
        default: 'add',
        type: String

    }

})
const weeksList = ref(WEEK_LIST)
// 年份
const yearOptions = yearFun()

const templateList = ref([]) // 预算模板展示数据

const templateListSave = ref([]) // 预算模板原始数据

const costCenterList = ref([]) // 成本中心

const dataForm = ref({
    budgetName: '',
    methods: '1',
    costCenterIdList: [],
    years: '',
    budgetType: 'COST',
    controlBy: 'CYCLE',
    cycleType: '',
    budgetRollEnabled: false,
    orgCode: '',
    orgName: '',
})

// 新增方式
const addMethods = ref([
    { label: '预算模板', value: '1' },
    { label: '自定义', value: '2' },
])

const companyOptions = ref([])

const loading = ref(false)

const rules = reactive({
    budgetName: [
        {
            required: true,
            message: '请输入',
            trigger: 'blur'
        },
        {
            min: 4,
            max: 50,
            required: true,
            message: '请输入4-50个字符',
            trigger: 'blur'

        }
    ],
    cycleType: [
        {
            required: true,
            message: '请选择',
            trigger: 'blur'
        }
    ],
    controlBy: [
        {
            required: true,
            message: '请选择',
            trigger: 'blur'
        }
    ],
    costCenterIdList: [
        {
            required: true,
            message: '请选择',
            trigger: 'blur'
        }
    ],
    years: [
        {
            required: true,
            message: '请选择',
            trigger: 'blur'
        }
    ],
    budgetRollEnabled: [
        {
            required: true,
            message: '请选择',
            trigger: 'blur'
        }
    ],

    budgetType: [
        {
            required: true,
            message: '请选择',
            trigger: 'blur'
        }
    ],
    budgetTemplateId: [
        {
            required: true,
            message: '请选择',
            trigger: 'blur'
        }
    ],
    date: [
        {
            required: true,
            message: '请选择',
            trigger: 'blur'
        }
    ],
    orgCode: [
        {
            required: true,
            message: '请选择',
            trigger: 'blur'
        }
    ]
})



const pageData = ref({
    pageNum: 1,
    pageSize: 1000
})

const formRef = ref(null)

const emit = defineEmits(['on-update', 'handleClose'])





watch(() => dataForm.value.controlBy, (newVal) => {
    if (newVal == 'CYCLE') weeksList.value = WEEK_LIST
    if (newVal == 'CUSTOM_TIME_RANGE') weeksList.value = TIME_WEEK_LIST
    dataForm.value.cycleType = ''
})
watch(() => dataForm.value.methods, (newVal) => {
    if (newVal == '1') dataForm.value.controlBy = 'CYCLE'

})


onMounted(() => {
    getTemplateList()


});

const selectCompany = (obj) => {
    dataForm.value.orgName = obj.fullName
    dataForm.value.orgCode = obj.orgCode
    //根据公司 code 查询成本中心
    getCostCenterList(obj.orgCode)
}

// 获取预算模板列表
const getTemplateList = () => {
    const parms = {
        ...pageData.value,
        enabled: true
    }
    api.budgetConfig.budgetTemplateList(parms).then(res => {
        const { list } = res
        templateList.value = list
        templateListSave.value = list

    })

}
// 选择预算类型
const selectBudgetType = (val) => {
    dataForm.value.orgName = ''
    dataForm.value.orgCode=''
}

// 选择年份
const selectYears = (val) => {
    dataForm.value.budgetTemplateId = ''
    let newList = templateListSave.value.filter(item => item.years.split(",").includes(val + '年'))
    templateList.value = newList

}

// 获取成本中心的数据
const getCostCenterList = (orgCode) => {
    const parms = {
        ...pageData.value,
        centerType: dataForm.value.budgetType,
        orgCode
    }
    api.budgetManger.CBcostCenterList(parms).then(res => {
        const { list } = res
            costCenterList.value = list
    })

}
// 关闭
const handleClose = () => {
    formRef.value.resetFields()
    formRef.value.clearValidate()
    emit('handleClose')

}

const submit = () => {
    const { controlBy, years, date, methods, orgCode,orgName } = dataForm.value
    console.log(orgName)
    if (!formRef) return
    formRef.value.validate(valid => {
        if (valid) {
            let data = {
                ...dataForm.value
            }
         
            if (controlBy == 'CYCLE') {
                //按年份
                data['startTime'] = `${years}-01-01 00:00:00`
                data['endTime'] = `${years}-12-31 23:59:59`
            } else {
                // 定义时间 
                data['startTime'] = date[0] + '-' + '01 00:00:00'
                // 获取对应月份的天数
                const dateStr = date[1].split("-")
                const days = new Date(dateStr[0], dateStr[1], 0).getDate()
                data['endTime'] = date[1] + '-' + days + ' 23:59:59'
            }
            if (methods == 2) {
                data['budgetTemplateId'] = null
            }
            delete data['date']
            api.budgetManger.budgetMangerAdd(data).then(res => {
                emit('on-update')
                handleClose()
                ElMessage.success('操作成功')
            })

        } else {
            console.log('error submit!')
            return false
        }
    })
}


</script>



<style lang="scss" scoped>
.w100p {
    width: 100%;
}

.prompt {
    margin: 0 20px;
    font-size: 14px;
}
</style>